﻿using dotnet_graphql_demo.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace dotnet_graphql_demo.Infrastructure
{
    public class OwnerRepository : IOwnerRepository,IAsyncDisposable
    {
        private readonly AppDbContext appDbContext;

        public OwnerRepository(IDbContextFactory<AppDbContext> dbContextFactory)
        {
            appDbContext = dbContextFactory.CreateDbContext();
        }

        public async Task<Owner> CreateOwnerAsync(Owner Owner)
        {
            await appDbContext.Owners.AddAsync(Owner);
            await appDbContext.SaveChangesAsync();
            return Owner;
        }

        public async Task<Owner> DeleteOwnerAsync(Owner Owner)
        {
            appDbContext.Owners.Remove(Owner);
            await appDbContext.SaveChangesAsync();
            return Owner;
        }

        public async Task<Owner> GetOwnerAsync(Guid id)
        {
            return await appDbContext.Owners.Where((c) => c.Id == id).FirstOrDefaultAsync();
        }

        public async Task<List<Owner>> GetOwnersAllAsync()
        {
            return await appDbContext.Owners.AsNoTracking().ToListAsync();
        }

        public async Task<Owner> UpdateOwnerAsync(Owner Owner)
        {
            appDbContext.Owners.Update(Owner);
            await appDbContext.SaveChangesAsync();
            return Owner;
        }

        public ValueTask DisposeAsync()
        {
            return appDbContext.DisposeAsync();
        }
    }
}